package org.myapp.service.login;

import org.myapp.constants.UserAuthority;
import org.myapp.datastore.AutoQuery;
import org.myapp.datastore.entity.User;
import org.myapp.datastore.model.UserModel;

import com.google.appengine.api.datastore.Entity;

/**
 * ログインサービスの実装クラス.<br>
 *
 * @author SASAKI
 */
public class LoginServiceImpl implements ILoginService {

    @Override
    public UserModel getUser(String user, String password) {

        AutoQuery query = new AutoQuery(User.ENTITY.getId());

        Entity entity = query.eq(User.COL_USER_ID.getId(), user).
                            eq(User.COL_PASSWORD.getId(), password).asSingle();

        if (entity != null) {
            return new UserModel(entity);
        }

        return null;
    }

    @Override
    public boolean isUseToken(String token) {

    	AutoQuery query = new AutoQuery(User.ENTITY.getId());

    	Entity entity = query.eq(User.COL_TOKEN.getId(), token).asSingle();

    	if (entity == null) {
    		return false;
    	}
    	return true;
    }

    @Override
    public boolean existUser(String userId) {

        AutoQuery query = new AutoQuery(User.ENTITY.getId());

        Entity entity = query.eq(User.COL_USER_ID.getId(), userId).asSingle();

        if (entity == null) {
            return false;
        }
        return true;
    }

    @Override
    public UserModel registUser(String user, String password) {

        UserModel model = new UserModel();
        model.setUserId(user);
        model.setPassword(password);
        model.setUserAuthority(UserAuthority.USER);
        model.save();

        return model;
    }
}
